﻿using System.Threading.Tasks;
using StockEngine.Extensions;
using StockEngine.RealTime;
using StockModel;
using System;
using Utils;

namespace StockEngine.Historical
{
	internal class GroupInitializer : GroupInitializerBase
	{
		#region Public Methods

		public GroupInitializer(StockGroupDataSource stockGroupDataSource, QuotationDataSource quotationDataSource, bool enableParallel) : base(stockGroupDataSource, quotationDataSource, enableParallel)
		{
		}

		public void InitializeAllGroups(DateTime day)
		{
			if (base.IsParallelEnabled)
			{
				Parallel.ForEach(this.Groups, item => this.InitializeGroup(item, day));	
			}
			else
			{
				foreach (EngineStockGroup engineStockGroup in this.Groups)
				{
					this.InitializeGroup(engineStockGroup, day);
				}
			}
		}

		#endregion

		#region Private Methods

		private void InitializeGroup(EngineStockGroup group, DateTime day)
		{
			group.ClearStocks();

			base.GroupDataSource.Load(group, day);
			this.GroupDataSource.LoadMarket(group);

			ObservableCollection2<StockGroupItem> items = group.Items.GetReadLock();
			try
			{
				if (base.IsParallelEnabled)
				{
					Parallel.ForEach(items, stockGroupItem => base.LoadDailyQuotationsToStock(group, stockGroupItem.Item, day));
				}
				else
				{
					foreach (StockGroupItem stockGroupItem in items)
					{
						base.LoadDailyQuotationsToStock(group, stockGroupItem.Item, day);
					}
				}
			}
			finally
			{
				group.Items.FreeReadLock();
			}

			group.IsInitialized = true;
		}

		#endregion
	}
}
